/* eslint-disable consistent-return */
/* eslint-disable array-callback-return */
/* eslint-disable react/no-array-index-key */
/* eslint-disable react/jsx-no-undef */
/* eslint-disable no-empty-pattern */
/**
 * 表格组件
 * 组件描述：根据入参生成表格，包括表格头部和表格主体，可以配置表格显示属性和表格列显示属性。
 * @author LiAnqi
 * @Date 2022.2.21
 */

/* eslint-disable no-debugger */
/* eslint-disable jsx-a11y/anchor-is-valid */
/* eslint-disable react/no-unstable-nested-components */
import React, { useState, useMemo, useEffect } from 'react'
import { Space, Row, Col, Menu, Table, Button } from 'antd'
import { UserOutlined, SettingOutlined } from '@ant-design/icons'
import { useMainContext } from '../index'
import FCRichLabel from '../fc-button/FCRichLabel'
import ConfigPanelForTable from './components/ConfigPanelForTable'
import ConfigPanelForColumns from './components/ConfigPanelForColumns'
import TableMain from './components/TableMain'
import ActionCell from './components/ActionCell'
import './FCTable.less'

function FCTablePanel(props) {
  // Props
  const {
    title,
    columns,
    dataSource,
    extraTopRight,
    actionColumn,
    pagination,
    rowKey,
    detailPage = { title: '详细页面' },
    onRowEvent,
  } = props
  // console.log(props)
  const { bordered, size, scroll, tableLayout } = props
  const [configurableProps, setConfigurableProps] = useState({
    bordered,
    size,
    scroll,
    tableLayout,
  })

  // State
  const [mergedColumns, setMergedColumns] = useState([...columns])
  const [ifConfigTable, setIfConfigTable] = useState(false)
  const [ifConfigColumns, setIfConfigColumns] = useState(false)

  // Hook
  const { onRequestTab } = useMainContext()

  // Method
  const showDrawerStyle = () => {
    setIfConfigTable(true)
  }

  const showConfigForColumns = () => {
    setIfConfigColumns(true)
  }

  // Event
  const onCloseDrawerColumns = () => {
    setIfConfigColumns(false)
  }

  const closeDrawerStyle = () => {
    setIfConfigTable(false)
  }

  const handleConfigColumns = ({ index, propName, checked }) => {
    const columnsCopy = [...mergedColumns]
    columnsCopy[index][propName] = checked
    setMergedColumns(columnsCopy)
  }

  const handleColumnsVisible = (e, columnIndex) => {
    const columnsCopy = [...mergedColumns]
    columnsCopy[columnIndex].open = e.target.checked
    setMergedColumns(columnsCopy)
  }

  const handleColumnsFixed = (e, columnIndex) => {
    const columnsCopy = [...mergedColumns]
    columnsCopy[columnIndex].fixed = e.target.checked
    setMergedColumns(columnsCopy)
  }

  const handleTableProps = (prop, value) => {
    const newProps = { ...configurableProps }
    newProps[prop] = value
    setConfigurableProps(newProps)
  }

  // Basic method
  const toDetail = ({ text, link, record }) => {
    const tabPane = {
      type: 'DetailPage',
      title: `${detailPage.title}-${text}`,
      key: `detail${new Date().getTime()}`,
      roote: link.roote,
      params: record,
    }
    onRequestTab(tabPane)
  }

  // Render
  const menuItems = [
    {
      key: '1',
      titil: '配置列',
      label: '配置列 ',
      onClick: (e) => {
        showConfigForColumns()
      },
    },
    {
      key: '2',
      titil: '设置显示风格',
      label: '设置显示风格 ',
      onClick: () => {
        showDrawerStyle()
      },
    },
  ]
  const popoverContent = (
    <Menu style={{ width: 200 }} mode="vertical" theme="light" items={menuItems} />
  )

  const colWithLink = (col) => {
    const { link } = col
    const mCol = {
      ...col,
      render: (text, record, rowIndex) => (
        <a
          href="#"
          onClick={() => {
            toDetail({ text, link, record })
          }}
        >
          {text}
        </a>
      ),
    }
    return mCol
  }

  const parseColumns = () => {
    const cols = []
    mergedColumns?.map((col) => {
      if (col.open) {
        const rCol = col.link ? colWithLink(col) : col
        cols.push(rCol)
      }
    })
    if (actionColumn) {
      const { title: actionTitlle, fixed, elements, ...rest } = actionColumn
      cols.push({
        ...rest,
        title: actionTitlle,
        fixed,//IE下无效
        key: 'actionCell9999',
        render: (_, record, index) => {
          return <ActionCell elements={elements} record={record} index={index} />
        },
      })
    }
    return cols
  }

  return (
    <div>
      <Row
        justify="space-around"
        className="table-header"
        style={{ line: '40px', lineHeight: '40px', backgroundColor: 'ddd' }}
      >
        <Col span={6}>
          <div className="table-header-title">{title}</div>
        </Col>
        <Col span={8}>
          <div />
        </Col>
        <Col span={10} style={{ textAlign: 'right', padding: '0 15px' }}>
          <Space direction="horizontal" align="end">
            {extraTopRight}
            <FCRichLabel
              size="48"
              text="配置"
              contentTitle=""
              icon={SettingOutlined}
              content={popoverContent}
              placement="bottomLeft"
            />
          </Space>
          <ConfigPanelForColumns
            ifVisible={ifConfigColumns}
            dataSource={mergedColumns}
            onClose={onCloseDrawerColumns}
            onChange={handleConfigColumns}
          />
          <ConfigPanelForTable
            ifVisible={ifConfigTable}
            onClose={closeDrawerStyle}
            tableProps={configurableProps}
            onChange={handleTableProps}
          />
        </Col>
      </Row>
      <TableMain
        {...configurableProps}
        columns={parseColumns(mergedColumns)}
        dataSource={dataSource}
        pagination={pagination}
        rowKey={rowKey}
        onRowEvent={onRowEvent}
      />
    </div>
  )
}
export default FCTablePanel
